package com.maple.admin.security.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.maple.admin.user.dto.RoleDTO;
import com.maple.admin.user.dto.UserDTO;
import com.maple.admin.user.service.IAccountService;

/**
 * base realm for requests inside application and RPC ones
 * @author luobenyu
 *
 */
public class BaseRealm extends AuthorizingRealm {
	
	public static final String MY_REALM_NAME = "baseRealm";
	
	@Autowired
	private IAccountService acctService;
	
	/* returns a unique name of current realm
	 * @see org.apache.shiro.realm.CachingRealm#getName()
	 */
	public String getName(){
		return MY_REALM_NAME;
	}
	
	/* only UsernamePasswordToken is supported here
	 * @see org.apache.shiro.realm.AuthenticatingRealm#supports(org.apache.shiro.authc.AuthenticationToken)
	 */
	public boolean supports(AuthenticationToken token){
		return token instanceof UsernamePasswordToken;
		
	}

	/* 进行授权
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		String userName = (String) SecurityUtils.getSubject().getPrincipal();
		UserDTO user = acctService.queryUserByLoginName(userName);
		for(RoleDTO role : user.getRoleList()){
			info.addRole(role.getRoleName());
			info.addStringPermission(role.getPermission());
		}
		return info;
	}

	/* 确认登录身份,这里返回从数据库查询得到的账户信息，与前端提交的进行比对
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		// TODO Auto-generated method stub
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;
		String userName = (String) token.getPrincipal();
		UserDTO userDTO = acctService.queryUserByLoginName(userName);
		if (userDTO != null) {
			char[] saltedPassword = userDTO.getUserPwd().toCharArray();
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, saltedPassword, this.getName());
			info.setCredentialsSalt(ByteSource.Util.bytes(userDTO.getUserSalt()));
			return info;
		}
		return null;
		
	}

}
